package vip.wangwenhao.common.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author wangwenhao
 */
public class MacEncryptUtils {


    /**
     * hash_hmac sha256
     *
     * @param data
     * @param key
     * @return
     */
    public static String getSignatureWithSHA256(String data, String key) {
        return getSignature(data, key, EncryptionAlgorithm.SHA256);
    }


    public static String getSignature(String data, String key, EncryptionAlgorithm encryptionAlgorithm) {
        StringBuilder sb = new StringBuilder();
        try {
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, encryptionAlgorithm.value);
            Mac mac = Mac.getInstance(encryptionAlgorithm.value);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            for (byte b : rawHmac) {
                sb.append(byteToHexString(b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static String byteToHexString(byte ib) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0f];
        ob[1] = Digit[ib & 0X0F];
        return new String(ob);
    }

    public enum EncryptionAlgorithm {
        /**
         *
         */
        SHA256("HmacSHA256"),
        SHA384("HmacSHA384"),
        SHA512("HmacSHA512"),
        SHA1("HmacSHA1"),
        MD5("HmacMD5"),
        ;

        private String value;

        EncryptionAlgorithm(String value) {
            this.value = value;
        }

    }
}